﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Markup;
using System.Windows;
using System.Globalization;
using System.Windows.Data;
using System.Xaml;
using System.Reflection;
using System.Windows.Media;

namespace Invini.Tools
{
    public class ResourceExtension : MarkupExtension
    {
        [ConstructorArgument("key")]
        public string Key
        {
            get;
            set;
        }

        public ResourceExtension() { }
        public ResourceExtension(string key)
        {
            this.Key = key;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if(String.IsNullOrEmpty(this.Key))
                throw new InvalidOperationException("Key is null or empty.");

            if (serviceProvider == null)
                throw new InvalidOperationException("Can't find root element.");

            IRootObjectProvider rootProvider = (IRootObjectProvider)serviceProvider.GetService(typeof(IRootObjectProvider));
            if(rootProvider == null)
                throw new InvalidOperationException("Can't find root element.");
            
            IResources root = rootProvider.RootObject as IResources;
            if(root == null)
                throw new InvalidOperationException("Root element must be a IResources instance.");

            if(root.Resources == null)
                throw new InvalidOperationException("Resource property is null.");

            return root.Resources[this.Key];
        }
    }
}
